package pl.textureStudio.view.panel.edit
{
	import pl.error.InternalError;
	import pl.textureStudio.data.vo.StudioTextureVO;

	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.net.URLRequest;

	/**
	 * @author michalr
	 */
	public class TextureView extends Loader
	{
		private var vo:StudioTextureVO;
		private var size:Point = new Point();
		private var completeHandler:Function;
		private static var isSecure:Boolean;

		public function TextureView()
		{
			if (isSecure == false) throw new Error( InternalError.CREATION_ERROR );
			contentLoaderInfo.addEventListener( Event.COMPLETE, onLoadComplete );
		}

		private function onLoadComplete( event:Event ):void
		{
			if (vo.texture == null)
			{
				var texture : Bitmap = (event.target as LoaderInfo).content as Bitmap;
				vo.textureSize = new Point(texture.width,texture.height);
				size = vo.textureSize.clone();
			}

			if (completeHandler != null) completeHandler();
		}

		private function initTexture():void
		{
			if (vo.texture == null)
				load( new URLRequest( vo.texturePath ) );
			else
				addChild( vo.texture );
		}

		public function setSize( sw:uint, sh:uint ):void
		{
			size.x = sw;
			size.y = sh;
		}

		public function getSize():Point
		{
			return size;
		}

		public static function factory( vo:StudioTextureVO, completeHandler : Function= null ):TextureView
		{
			isSecure = true;
			var o:TextureView = new TextureView();
			o.completeHandler = completeHandler;
			o.vo = vo;
			o.initTexture();
			o.size = vo.textureSize.clone();
			return o;
		}
	}
}
